<?php
/*
 * File:LinkBiz.php
 * Created:2013-5-17
 * Author:oldjiang
 * 
 */
class LinkBiz{
	private $linkDAO;
	private $historyBiz;
	private $sLogBiz;
	//搜索分词
	private $keywordArray;
	//查询方式，按标题查询还是全文查询
	private $type;
	//查询模块，文章、帖子、日志等
	private $mod;
	//查询语句数组
	private $sqlArray=array();
	//查询结果数组
	private $searchResult=array();
	//查询到的记录总数
	private $searchTotal=0;
	
	/**
	 * 构造方法
	 */
	function LinkBiz(){
		$this -> linkDAO = new LinkDAO();
		$this -> historyBiz =new HistoryBiz();
		$this -> sLogBiz = new SLogBiz();
	}
	/**
	 * 新增一条记录
	 */
	function add($linkVO){
		$linkPO = $linkVO;
		$this -> linkDAO ->add($linkPO);
	}
	
	/**
	 * 更新一条记录
	 */
	function update($linkVO){
		$linkPO = $linkVO;
		//判断当前URL在数据库中是否存在
		if($this -> linkDAO -> getOneByUrl($linkPO -> getUrl())==null){
			$this -> linkDAO ->add($linkPO);
		}else{
			$this -> linkDAO ->update($linkPO);
		}
	}
	
	/**
	 * 新增多条记录
	 * $array ArraySet类型，可查看lib/array.class.php文件
	 */
	function addArraySet($array){
		$arraySet = $array -> read();
		for($i=0;$i<count($arraySet);$i++){
			$this->add($arraySet[$i]);
		}
	}
	
	/**
	 * 更新多条记录
	 * $array ArraySet类型，可查看lib/array.class.php文件
	 */
	function updateArraySet($array){
		$arraySet = $array -> read();
		for($i=0;$i<count($arraySet);$i++){
			$this->update($arraySet[$i]);
		}
	}
	
	/**
	 * 搜索结果总数
	 */
	private function total(){
		//与getSearchResult、makeSearchResult和makeSQL配合使用
		//return count($this -> searchResult);
		//关键词所属模块
		$sql_mod = $this -> getKeyWordsModSql();
		$sql = $sql_mod.join(' And ',$this -> sqlArray);
		$total = $this -> linkDAO -> total($sql);
		$this -> searchTotal = $total;
	}
	
	function getmicrotime(){
	    list($usec, $sec) = explode(" ",microtime());
	    return ((float)$usec + (float)$sec);
    }
	
	/**
	 * 搜索入口
	 * $keyword 关键词
	 * $page 页码
	 * $num_per_page 每页记录数
	 */
	function search($keyword,$type,$mod,$page,$num_per_page='10'){
		$this -> type = $type;
		$this -> mod = $mod;
		if($page<1){
			$page = 1;
		}
		if($this -> mod =="" ){
			$this -> mod = -1;
		}
		//关键词分词
		$this -> setKeywordArray($keyword);
		if(count($this -> keywordArray)<1){
			return array();
		}
		//构建SQL条件语句
		$this -> getKeyWordsSql();
		//返回部分信息给用户用于显示(带页码)
		$this -> total();
		$keyWordsResult = $this -> getKeyWordsResult($page,$num_per_page);
		$this -> updateSearchHistory($keyword);
		return $keyWordsResult;
	}
	
	/**
	 * 更新搜索历史
	 */
	function updateSearchHistory($keyword){
		$httpd = new httpd();
		$robot = new checkrobot();
		//添加搜索日志
		$sLogVO = new SLogVO();
		$sLogVO -> setKeyword($keyword);
		$sLogVO -> setResult($this -> searchTotal);
		$sLogVO -> setLasttime(time());
		$sLogVO -> setLastip($httpd -> getIp());
		$sLogVO -> setMod($this -> mod);
		$sLogVO -> setIsRobot($robot -> isRobot());
		$this -> sLogBiz -> addLog($sLogVO);
		//添加搜索关键词历史记录
		$historyVO = $this -> historyBiz -> getHistory($keyword);
		if($historyVO -> getId()==null){
			//没有该搜索记录则添加
			$historyVO = new HistoryVO();
			$historyVO -> setKeyword($keyword);
			$historyVO -> setSpwords(join($this -> keywordArray,' '));
			$historyVO -> setCount(1);
			$historyVO -> setResult($this -> searchTotal);
			$historyVO -> setLasttime(time());
			$historyVO -> setLastip($httpd -> getIp());
			$historyVO -> setMod($this -> mod);
			$this -> historyBiz -> add($historyVO);
		}else{
			//拥有该搜索记录则更新
			$historyVO -> setLastip($httpd -> getIp());
			$historyVO -> setMod($this -> mod);
			$historyVO -> setResult($this -> searchTotal);
			$historyVO -> setLasttime(time());
			$historyVO -> setLastip($httpd -> getIp());
			$historyVO -> setMod($this -> mod);
			$this -> historyBiz -> updateCount($historyVO);
		}
	}
	
	/**
	 * 获取数据库内的数据
	 * 使用优化的SQL语句以提高数据库limit关键词查询效率
	 * SELECT * FROM link WHERE CONCAT(title,' ',content) LIKE '%小学%' AND id<=(SELECT MIN(id) FROM (SELECT id FROM link WHERE CONCAT(title,' ',content) LIKE '%小学%' ORDER BY id DESC LIMIT 0,1) AS tmp) ORDER BY id DESC LIMIT 10;
	 */
	function getKeyWordsResult($page,$num_per_page='10'){
		//从第多少条记录开始显示
		$start = ($page-1)*$num_per_page;
		//相关性排序
		$sql_relitive = $this -> getKeyWordsOrderBy();
		//关键词所属模块
		$sql_mod = $this -> getKeyWordsModSql();
		//$sql = "select * from link where ".join(' And ',$this -> sqlArray)." AND id<=(SELECT MIN(id) FROM (SELECT id FROM link WHERE ".join(' And ',$this -> sqlArray)." ORDER BY ".$sql_relitive." id DESC LIMIT $start,1) AS tmp) ORDER BY ".$sql_relitive." id DESC LIMIT $num_per_page";
		$sql = $sql_mod.join(' And ',$this -> sqlArray)." ORDER BY ".$sql_relitive." time DESC LIMIT $start,$num_per_page";
		$keyWordsResult = $this -> searchResult[count($this -> searchResult)] = $this -> linkDAO -> search($sql);
		return $keyWordsResult;
	}
	
	/**
	 * 组织关键词模块SQL语句
	 */
	function getKeyWordsModSql(){
		$sql_mod = "";
		if($this->mod != "" && $this->mod > 0){
			$sql_mod = "`mod` = ".$this->mod." And ";
		}
		return $sql_mod;
	}
	
	/**
	 * SQL语句 相关性排序
	 */
	function getKeyWordsOrderBy(){
		$sql_relitive = "(";
		$sql_title = array();
		for($i=0;$i<count($this -> keywordArray);$i++){
			$sql_title[] = " title like '%".$this -> keywordArray[$i]."%' ";
		}
		$sql_relitive .= "CASE WHEN title = '".join('',$this -> keywordArray)."' THEN 4 WHEN title like '%".join('',$this -> keywordArray)."%' THEN 3 WHEN ".join(' And ',$sql_title)." THEN 2 WHEN ".join(' OR ',$sql_title)." THEN 1 ELSE 0 END";
		$sql_relitive .= ") desc,";
		return $sql_relitive;
	}
	
	/**
	 * 组织SQL语句
	 */
	function getKeyWordsSql(){
		//分词
		for($i=0;$i<count($this -> keywordArray);$i++){
			if($this -> type == "t"){
				$this -> sqlArray[count($this -> sqlArray)] = " title like '%".$this -> keywordArray[$i]."%' ";
			}else{
				$this -> sqlArray[count($this -> sqlArray)] = " CONCAT(title,' ',content) like '%".$this -> keywordArray[$i]."%' ";
			}
		}
	}
	
	/**
	 * 搜索返回结果
	 * 与makeSearchResult和makeSQL配合使用
	 */
	function getSearchResult($page,$num_per_page='10'){
		//从第多少条记录开始显示
		$start = ($page-1)*$num_per_page;
		$searchResult = array();
		//遍历出需要显示的数据
		for($i=$start;$i<$start+$num_per_page && $i<count($this -> searchResult);$i++){
			$searchResult[count($searchResult)] = $this -> searchResult[$i];
		}
		return $searchResult;
	}
	
	/**
	 * 搜索结果处理，排除重复
	 * 与makeSearch和makeSQL配合使用
	 * 数组太大，耗硬件资源，处理速度较慢，暂不考虑使用
	 */
	function makeSearchResult(){
		$tempResult = $this -> searchResult;
		$this -> searchResult = array();
		$k=0;
		//遍历查询语句
		for($i=0;$i<count($tempResult);$i++){
			//遍历查询语句获得的结果
			for($j=0;$j<count($tempResult[$i]);$j++){
				//标志当前记录是否重复
				$flag = false;
				//遍历已存在的记录与当前记录对比
				for($z=0;$z<count($this -> searchResult);$z++){
					if($this -> searchResult[$z]['id'] == $tempResult[$i][$j]['id']){
						//已存在一直记录
						$flag = true;
					}
				}
				//如果不存在该记录，则加入到数组中
				if(!$flag){
					$this -> searchResult[count($this -> searchResult)] = $tempResult[$i][$j];
				}
			}
		}
	}
	
	/**
	 * 组织SQL语句
	 * 与makeSearch和makeSearchResult配合使用
	 * SQL语句太多，效率可能会低，暂不使用
	 */
	function makeSQL($column){
		$all = "";
		$and = "";
		$or = "";
		//根据关键词分出的分词数组组织SQL语句
		for($i=0;$i<count($this -> keywordArray);$i++){
			if($i==0){
				$all .= $column." like('%".$this -> keywordArray[$i];
				$and .= $column." like('%".$this -> keywordArray[$i]."%')";
				$or .= $column." like('%".$this -> keywordArray[$i]."%')";
			}else{
				$all .= $this -> keywordArray[$i];
				$and .= "and ".$column." like('%".$this -> keywordArray[$i]."%')";
				$or .= "or ".$column." like('%".$this -> keywordArray[$i]."%')";
			}
			if($i==count($this -> keywordArray)-1){
				$all .= "%')";
			}
		}
		$this -> sqlArray[count($this -> sqlArray)] = $all;
		$this -> sqlArray[count($this -> sqlArray)] = $and;
		$this -> sqlArray[count($this -> sqlArray)] = $or;
	}
	
	/**
	 * 关键词分词
	 */
	function setKeywordArray($keyword){
		$pa = new PhpAnalysis('utf-8', 'utf-8');
		$pa->LoadDict();
		$pa->SetSource($keyword);
		$pa->StartAnalysis(true);
		$result = explode(" ",$pa->GetFinallyResult(' ', false));
		for($i=0;$i<count($result);$i++){
			if($result[$i] != "" && $result[$i] != " ")
			$this -> keywordArray[count($this -> keywordArray)] = $result[$i];
		}
	}
	
	/**
	 * 获取关键词分词数组
	 */
	public function getKeywordArray(){
		return $this -> keywordArray;
	}
	/**
	 * 获取查询到的记录总数
	 */
	public function getSearchTotal(){
		return $this -> searchTotal;
	}
}
?>
